//
//  MFWDownloadDBHelp+FixAbsolutePath.m
//  TravelGuideHD
//
//  Created by xiaofeng on 15/1/9.
//  Copyright (c) 2015年 mafengo Inc. All rights reserved.
//

#import "MFWDownloadDBHelp+FixAbsolutePath.h"

#define  kDownloadDB_Version_FixFilePath  1

@interface MFWDownloadDBHelp(Private)

@property (nonatomic, copy)NSString *dbPath;

- (int)latestDBVersion;
+ (BOOL)setDBVersion:(NSString*)verision widthDescription:(NSString*)desc db:(FMDatabase *)db;
@end

@implementation MFWDownloadDBHelp (FixAbsolutePath)

- (BOOL)shouldUpgradeToRelativeFilePath
{
    int dbVersion = [self latestDBVersion];
    return (dbVersion < kDownloadDB_Version_FixFilePath);
}

- (BOOL)fixAbsoluteFilePathFromAppVersion;
{
    if ([self shouldUpgradeToRelativeFilePath])
    {
        [self upgradeDowloadTaskTableToUsingRelativeFilePath];
        return YES;
    }
    return NO;
}

+ (NSString*)relativeHomePathForLibraryAbsolutePath:(NSString*)absPath
{
    NSRange range = [absPath rangeOfString:@"/Library/" options:NSBackwardsSearch];
    if (range.location != NSNotFound)
    {
        return [absPath substringFromIndex:(range.location)];
    }
    else
    {
        return nil;
    }
}

- (void)upgradeDowloadTaskTableToUsingRelativeFilePath
{
    FMDatabaseQueue *queue = [[FMDatabaseQueue alloc] initWithPath:self.dbPath];
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL success = YES;
        
        NSString *sql = [NSString stringWithFormat:@"select * from DownloadTasks"];
        FMResultSet *set = [db executeQuery:sql];
        
        int count = 0;
        while ([set next])
        {
            NSString *taskId = [set stringForColumn:@"ID"];
            NSString *localPath = [set stringForColumn:@"LocalPath"];
            NSString *tempPath = [set stringForColumn:@"TempPath"];
            
            NSString *relativeLocalPath = [MFWDownloadDBHelp relativeHomePathForLibraryAbsolutePath:localPath];
            NSString *relativeTempPath = [MFWDownloadDBHelp relativeHomePathForLibraryAbsolutePath:tempPath];
            
            if (taskId && relativeLocalPath && relativeLocalPath)
            {
                sql = [NSString stringWithFormat:@"UPDATE DownloadTasks SET LocalPath='%@', TempPath='%@' WHERE ID=%@", relativeLocalPath, relativeTempPath, taskId];
                success = success && [db executeUpdate:sql];
                if (success)
                {
                    count++;
                }
            }
        }
        
        success = success && [MFWDownloadDBHelp setDBVersion:[NSString stringWithFormat:@"%d", kDownloadDB_Version_FixFilePath]
                                            widthDescription:@"绝对路径改为相对路径"
                                                          db:db];
        
        DLog(@"update download task table %@ with count:%d", success?@"YES":@"NO", count);
        
        *rollback = !success;
    }];
}
@end
